package com.sprite.utils.http.payload;

import com.sprite.utils.http.ContentType;
import com.sprite.utils.http.RequestPayload;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

/**
 * @author Jack
 * @since 1.2.4
 */
public class RawData implements RequestPayload {

    private StringBuffer content = new StringBuffer();

    private ContentType contentType;

    public void append(CharSequence charSequence) {
        content.append(charSequence);
    }

    @Override
    public void writePayload(OutputStream outputStream) throws IOException {
        String charset = contentType != null ? contentType.getCharset() : Charset.defaultCharset().name();
        outputStream.write(content.toString().getBytes(charset != null ? charset : Charset.defaultCharset().name()));
    }

    /**
     * 设置 content type
     *
     * @param contentType
     *         ContentType
     */
    public void setContentType(ContentType contentType) {
        this.contentType = contentType;
    }

    /**
     * 设置 content type
     *
     * @param contentType
     *         content type string
     */
    public void setContentType(String contentType) {
        if( this.contentType == null){
            this.contentType = new ContentType();
        }
       this.contentType.setMediaType(contentType);
    }

    /**
     * 获取 content type
     *
     * @return
     */
    @Override
    public ContentType getContentType() {
        return this.contentType;
    }

}
